/*
 * @Author: xiaosihan 
 * @Date: 2023-08-31 22:31:30 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-07-18 18:04:09
 */

import textApi from "@/api/textApi";
import Taro from "@tarojs/taro";
import { toJS } from "mobx";
import { makeAutoObservable } from "mobx";
import utils from "src/utils/utils";
import { FontData } from "types/type";
// 移除对不存在模块的引用
// import textApi from "../TextModel/textModelApi";
class FontManage {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });

        this.getNextPage(true);
    }

    // 加载中的字体
    loadingFonts: Array<string> = [];
    // 添加加载中的字体
    addLoadingFont(font: string) {
        this.loadedFonts = toJS(this.loadedFonts).filter(f => f !== font);
        this.loadErrFonts = toJS(this.loadErrFonts).filter(f => f !== font);
        this.loadingFonts = [font, ...toJS(this.loadingFonts)];
    }

    // 加载完成的字体
    loadedFonts: Array<string> = [];
    // 添加加载完成的字体
    addLoadedFont(font) {
        this.loadingFonts = toJS(this.loadingFonts).filter(f => f !== font);
        this.loadedFonts = [font, ...toJS(this.loadedFonts)];
    }

    //加载失败的字体
    loadErrFonts: Array<string> = [];
    addLoadErrFonts(font) {
        this.loadingFonts = toJS(this.loadingFonts).filter(f => f !== font);
        this.loadErrFonts = [font, ...toJS(this.loadErrFonts)];
    }

    // 是否有在加载字体
    hasLoad(fontName) {
        return (this.loadingFonts.includes(fontName) || this.loadedFonts.includes(fontName));
    }

    // 卸载无用的字体, 保留有用的字体
    unloadFont(saveFontName: Array<string>) {
        // 找出需要卸载的字体
        const needUnloadFont = this.loadedFonts.filter(f => saveFontName.includes(f));
        // 卸载字体
    }

    // 字体配置列表
    fontlist: Array<FontData> = [];

    // 获取字体图片
    getFontImg(fontName: string) {
        const fontC = this.fontlist.find(f => f.fontName === fontName);
        if (fontC) {
            return fontC.fontImageUrl;
        }
        return "";
    }

    // 加载字体
    async loadFont(fontIds) {


        // 等待字体列表加载完成
        while (this.loading) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }

        // 获取字体详情
        const res = await textApi.getFontsById(fontIds);

        res.data.map(f => {
            if (!this.hasLoad(f.fontName)) {
                // 字体加载中的状态
                this.addLoadingFont(f.fontName);
                // 用Taro的字体加载方式
                Taro.loadFontFace({
                    family: f.fontName, // 字体名称
                    source: `url("${utils.ossSuffix(f.fontFileUrl)}")`, // 字体文件路径
                    success: () => { // 字体
                        // console.log("加载字体成功", f.fontName, f.fontFileUrl);
                        this.addLoadedFont(f.fontName);
                    },
                    fail: (err) => {
                        // console.log("加载字体失败", f.fontName, f.fontFileUrl);

                        this.addLoadErrFonts(f.fontName);
                    },
                    complete: () => { },
                    global: true, // 是否全局加载，默认为 false
                })
            }

        });

        // 等待字体加载完成
        while (fontManage.loadingFonts.length) {
            await new Promise(resolve => setTimeout(resolve, 30));
        }

    }


    //加载中字体列表中
    loading = true;
    setLoading(loading: boolean) {
        this.loading = loading;
    }

    page = 1;
    pageSize: number = 999;
    hasNext: boolean = true;

    async getNextPage(reset: boolean = false) {
        if (reset) {
            this.page = 1;
            this.hasNext = true;
        } else if (!this.hasNext || this.loading) {
            return;
        } else {
            this.page++;
        }
        this.loading = true;

        // 移除对不存在模块的引用
        const result = await textApi.getFonts(this.page, this.pageSize);

        if (result?.rows) {
            if (reset) {
                this.fontlist = [];
                await new Promise(resolve => requestAnimationFrame(resolve));
                await new Promise(resolve => requestAnimationFrame(resolve));
                await new Promise(resolve => requestAnimationFrame(resolve));
                this.fontlist = [...result.rows];
            } else {
                this.fontlist = [...this.fontlist, ...result.rows];
            }
            this.hasNext = (result.rows.length === this.pageSize);
            this.loading = false;
        }

    }


}

const fontManage = new FontManage();

export default fontManage;

